package com.freedom.rpc.thrift.client;

import java.lang.reflect.Method;

import org.apache.thrift.TException;
import org.apache.thrift.protocol.TBinaryProtocol;
import org.apache.thrift.protocol.TMultiplexedProtocol;
import org.apache.thrift.protocol.TProtocol;
import org.apache.thrift.transport.TFramedTransport;

import com.freedom.rpc.thrift.client.socket.MyTSocket;
import com.freedom.rpc.thrift.client.socket.TSocketPool;
import com.freedom.rpc.thrift.common.service.HelloWorldService;
import com.freedom.rpc.thrift.common.utils.Logger;

public class MyClient {

	private static final Logger logger = Logger.getLogger(MyClient.class);

	public static void main(String[] args) {
		try {
			test();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	public static void test() throws Exception {

		MyTSocket socket = null;
		socket = TSocketPool.getInstance().borrowObject();
		if (null == socket) {
			throw new Exception("fail to fetch a socket from pool...");
		}
		try {
			TMultiplexedProtocol tMultiProtocol = new TMultiplexedProtocol(
					new TBinaryProtocol(new TFramedTransport(socket)), "HelloWorldService");
			// 具体实现类
			HelloWorldService.Client client = new HelloWorldService.Client(tMultiProtocol);
			//
			// 接下来，可以调用你自己在.thrift文件里定义的方法
			// [由于thrift把一些内部方法也定义为public
			// 所以调用时注意只调用自己定义的接口方法，其它不要调用，以免出错]
			long start = System.currentTimeMillis();
			System.out.println("client.helloBoolean(false)---" + client.helloWorldBoolean(3));
			logger.debug("耗时：" + (System.currentTimeMillis() - start) + " ms");
			//
		} catch (Exception e) {
			logger.error(e.toString());
			// 通过业务侧，我们也做了连接可用性的探测
			socket.setAlive(false);
			throw e;
		} finally {
			TSocketPool.getInstance().returnObject(socket);
		}
	}
}
